import request from '@/utils/request';
import { setToken, removeToken } from '@/utils/token-util';
import type { ApiResult } from '@/api';
import type { LoginParam, LoginResult, CaptchaResult } from './model';

/**
 * 登录
 */
export async function login(data: LoginParam) {
  data.tenantId = 2; // 租户id
  const res = await request.post<ApiResult<LoginResult>>(
    '/sysAuth/login',
    data
  );
  if (res.data.code === 200) {
    setToken(res.data.result?.accessToken, data.remember);
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取验证码
 */
export async function getCaptcha() {
  const res = await request.get<ApiResult<CaptchaResult>>('/sysAuth/captcha');
  if (res.data.code === 200 && res.data.result) {
    return res.data.result;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 退出登录
 * @param data
 * @returns
 */
export async function logout() {
  const res = await request.post<ApiResult<LoginResult>>('/sysAuth/logout');
  if (res.data.code === 200) {
    removeToken();
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
